package com.ddch.udpsocket.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.List;

/**
 * created by 韦敏敏
 * on 2019/12/18
 */
public class DeviceUtil {
    @SuppressLint("WrongConstant")
    public synchronized static String getDeviceId(Context context){
        if(context == null)
            return "";
        String imei = "";
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        try {
            if(tm == null || TextUtils.isEmpty(tm.getDeviceId())) {
                tm = (TelephonyManager) context.getSystemService("phone1");
            }
            if(tm != null)
                imei = tm.getDeviceId();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return imei;
    }
    @SuppressLint("MissingPermission")
    public synchronized static String getSimSerialNumber(Context context){
        if(context == null)
            return "";
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getSimSerialNumber();
    }
    public synchronized static String getAndroidID(Context context){
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    /**
     * 操作系统版本
     * @return
     */
    public static String getOSversion(){
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 设备商
     * @return
     */
    public static String getManufacturer(){
        return Build.MANUFACTURER;
    }

    /**
     *  设备型号
     * @return
     */
    public static String getModel(){
        return Build.MODEL;
    }

    /**
     * 序列号
     * @return
     */
    public static String getSerialNumber(){
        String serial = null;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
        } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return serial;
    }

    /**
     *  SD CARD ID
     * @return
     */
    public static synchronized String getSDcardID(){
        try {
            String sdCid = null;
            String[] memBlkArray = new String[]{"/sys/block/mmcblk0","/sys/block/mmcblk1","/sys/block/mmcblk2"};
            for(String memBlk : memBlkArray){
                File file = new File(memBlk);
                if(file.exists() && file.isDirectory()){
                    Process cmd = Runtime.getRuntime().exec("cat " + memBlk + "/device/cid");
                    BufferedReader br = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
                    sdCid = br.readLine();
                    if(!TextUtils.isEmpty(sdCid)){
                        return sdCid;
                    }
                }
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 获取 mac 地址
     * @param context
     * @return
     */
    public static String getMac(Context context){
        if(context == null)
            return "";
        String mac = null;
        try {
            final WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if(wifi != null){
                WifiInfo info = wifi.getConnectionInfo();
                if(null != info && info.getMacAddress() != null){
                    mac = info.getMacAddress();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mac;
    }

    /**
     *  获取mac地址
     *  可以突破android6.0d的限制
     * @return
     */
    public static String getWifiMacAddress(){
        try {
            String interfaceName = "wlan0";
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces){
                if(!intf.getName().equalsIgnoreCase(interfaceName)){
                    continue;
                }
                byte[] mac = intf.getHardwareAddress();
                if(mac == null)
                    return "";
                StringBuilder buf = new StringBuilder();
                for(byte aMac : mac){
                    buf.append(String.format("%02X:", aMac));
                }
                if(buf.length() > 0){
                    buf.deleteCharAt(buf.length() -1);
                }
                return buf.toString();
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取屏幕的分辨率
     * @param context
     * @return
     */
    public static int[] getScreemResolution(Context context){
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int[] resolution = new int[2];
        resolution[0] = dm.widthPixels;
        resolution[1] = dm.heightPixels;
        return resolution;
    }
    public static String getPackageVersion(Context context){
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static int getPackageVersionCode(Context context){
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
